package com.leetcodehot.problems;

public class problems129 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 返回从root的所有数字之和
     * 一、确定函数的两个参数 当前root和父节点需要继承的值
     * 二、确定题目条件是叶子节点，作为返回值
     * 三、微操作：当前节点的值 等于 左子树代表的数字和右子数代表的数字之和
     */
    public int dfs(TreeNode root, int last) {
        last = last * 10 + root.val;
        if (root.left == null && root.right == null) return last;
        int left = 0, right = 0;
        if (root.left != null) {
            left = dfs(root.left, last);
        }
        if (root.right != null) {
            right = dfs(root.right, last);
        }
        return left + right;
    }


    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }
}
